import socket
import re
from utils.protocol_flags import ProtocolFlags
from utils.rtfparser import RTFParser
from utils.logger import get_logger

class DataProcessor:
    def __init__(self, client_socket: socket.socket):
        self.client_socket = client_socket
        self.buffer = bytearray()
        self.is_collecting = False
        self.expected_length = 0
        self.logger = get_logger(__name__)
        
        # 定义处理器映射
        self.handlers = {
            ProtocolFlags.FEI_KONG_FLAG: lambda data: self._send_response(
                ProtocolFlags.FEI_KONG_REPLY_FLAG, "飞控标志位"
            ),
            ProtocolFlags.CARD_TYPE_CHECK_FLAG: lambda data: self._send_response(
                ProtocolFlags.CARD_TYPE_CHECK_REPLY, "卡类型检查"
            ),
            ProtocolFlags.DATA_SEND_FLAG: lambda data: self._send_response(
                ProtocolFlags.DATA_SEND_REPLY_FLAG, "数据发送"
            )
        }

    def process_data(self, data: bytes) -> None:
        """处理接收到的数据"""
        # 特殊情况优先处理
        if data.startswith(ProtocolFlags.FEI_KONG_CONTENT_START):
            self.is_collecting = True
            self.buffer.clear()  # 清空之前的缓冲区
            return self._handle_content_start(data)
        
        # 如果是停止标志，处理停止
        if data == ProtocolFlags.FEI_KONG_CONTENT_STOP:
            return self._handle_content_stop(data)
            
        # 如果正在收集数据，所有数据都加入buffer
        if self.is_collecting:
            # self.logger.info(f"正在收集数据，添加到缓冲区: {data.hex()}")
            return self._handle_content_data(data)
            
        # 使用字典处理其他常规情况
        handler = self.handlers.get(data)
        if handler:
            handler(data)
        else:
            self.logger.warning(f"收到未知数据包: {data.hex()}")

    def _handle_content_start(self, data: bytes) -> None:
        """处理内容开始标志"""
        self.buffer.extend(data)  # 将开始标志也加入到buffer中
        self.client_socket.send(ProtocolFlags.DATA_CONTENT_REPLY)
        if len(data) >= 12:
            self.expected_length = int.from_bytes(data[8:12], byteorder='little')
            self.logger.info(f'预期数据长度: {self.expected_length} 字节')

    def _handle_content_stop(self, data: bytes) -> None:
        """处理内容停止标志"""
        if not self.is_collecting:
            return

        self.client_socket.send(ProtocolFlags.DATA_CONTENT_REPLY_STOP)
        
        try:
            decoded_data = self.buffer.decode('utf-8', errors='ignore')
            
            # 查找RTF内容
            rtf_pattern = r'({\\rtf1.*?\\par\s*})'
            if match := re.search(rtf_pattern, decoded_data, re.DOTALL | re.MULTILINE):
                rtf_content = match.group(1)
                self.logger.info(f'提取的RTF内容: {rtf_content}')
                # 直接使用清理后的RTF内容
                parsed_rtf = RTFParser.parse(rtf_content)
                self.logger.info(f'解析结果: {parsed_rtf["content"]}')
            else:
                self.logger.warning('未找到RTF内容')
            
        except Exception as e:
            self.logger.error(f'RTF内容提取失败: {e}')

        # 重置状态
        self.is_collecting = False
        self.buffer.clear()
        self.expected_length = 0

    def _handle_content_data(self, data: bytes) -> None:
        """处理内容数据"""
        try:
            self.logger.debug(f'数据包解码: {data.decode("utf-8", errors="ignore")}')
        except Exception as e:
            self.logger.error(f'数据包解码失败: {e}')
            
        self.buffer.extend(data)
        try:
            self.logger.debug(f'当前buffer解码: {self.buffer.decode("utf-8", errors="ignore")}')
        except Exception as e:
            self.logger.error(f'buffer解码失败: {e}')
            
        self.client_socket.send(ProtocolFlags.DATA_CONTENT_REPLY_2)

    def _process_complete_data(self) -> None:
        """处理完整的数据"""
        try:
            decoded_data = self.buffer.decode('utf-8', errors='ignore')
            # 直接匹配RTF内容
            pattern = r'({\\rtf1.*?\\par\s*})'
            if match := re.search(pattern, decoded_data, re.DOTALL | re.MULTILINE):
                rtf_content = match.group(1)
                self.logger.info(f'提取到的RTF内容: {rtf_content[:100]}...')
                parsed_rtf = RTFParser.parse(rtf_content)
                self.logger.info(f'解析结果: {parsed_rtf["content"]}')
            else:
                self.logger.warning('未找到RTF内容')
        except Exception as e:
            self.logger.error(f'数据处理失败: {e}')

    def _send_response(self, response: bytes, description: str) -> None:
        """发送响应"""
        try:
            self.client_socket.send(response)
            self.logger.info(f'已发送{description}响应')
        except socket.error as e:
            self.logger.error(f'发送{description}响应时出错: {e}')

